package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"iot-base/common/cache"
	"time"
)

func request(c *gin.Context) {
	fmt.Println("request!")
	now := time.Now().Unix()
	params := c.Request.URL.Query()
	SN := params.Get("SN")
	cache.SetLastAliveTime(Registtable[SN].devid, now)
	switch Order {
	case sendCard:
		fmt.Println("card =", card)
		fmt.Println("step:", sc1)
		if sc1.step1 && card != 0 {
			fmt.Println("send card 1 step --------------------------")
			c.Writer.Write([]byte(fmt.Sprintf(`C:10:DATA UPDATE user CardNo=%v	Pin=%v	Password=1234	Group=0	StartTime=0	EndTime=0	Name=%v	SuperAuthorize=0	Disable=0`, card, card, card))) //发卡
			sc1.step1 = false
			return
		}
		if sc1.step2 && card != 0 {
			fmt.Println("send card 2 step --------------------------")
			c.Writer.Write([]byte(fmt.Sprintf(`C:11:DATA UPDATE userauthorize Pin=%v	AuthorizeTimezoneId=1	AuthorizeDoorId=3`, card)))
			sc1.step2 = false
			card = 0
			return
		}
		if sc1.step3 {
			fmt.Println("send card 3 step --------------------------")
			c.Writer.Write([]byte(`C:12:DATA UPDATE timezone TimezoneId=1	SunTime1=2359	SunTime2=0	SunTime3=0	MonTime1=2359	MonTime2=0	MonTime3=0	TueTime1=2359	TueTime2=0	TueTime3=0	WedTime1=2359	WedTime2=0	WedTime3=0	ThuTime1=2359	ThuTime2=0	ThuTime3=0	FriTime1=2359	FriTime2=0	FriTime3=0	SatTime1=2359	SatTime2=0	SatTime3=0	Hol1Time1=2359	Hol1Time2=0	Hol1Time3=0	Hol2Time1=2359	Hol2Time2=0	Hol2Time3=0	Hol3Time1=2359	Hol3Time2=0	Hol3Time3=0`))
			sc1.init()
			Order = 0
			card = 0
			return
		}
	case queryCard:
		c.Writer.Write([]byte(`C:55:DATA QUERY tablename=user,fielddesc=*,filter=*`))
		Order = 0
		return
	case deleteCard:
		if dc1.step1 {
			fmt.Println("delete 1 step --------------------------")
			c.Writer.Write([]byte(fmt.Sprintf(`C:60:DATA DELETE userauthorize Pin=%v`, card)))
			dc1.step1 = false
			return
		}
		if dc1.step2 {
			fmt.Println("delete 2 step --------------------------")
			c.Writer.Write([]byte(fmt.Sprintf(`C:70:DATA DELETE user Pin=%v`, card)))
			dc1.init()
			Order = 0
			return
		}
	case openDoor:
		fmt.Println("open door!")
		c.Writer.Write([]byte(`C:80:CONTROL DEVICE 01020101`))
		Order = 0
		return
	case closeDoor:
		fmt.Println("close door!")
		c.Writer.Write([]byte(`C:90:CONTROL DEVICE 01010101`))
		Order = 0
		return
	default:
		c.Writer.Write([]byte("OK"))
	}
}
